
<div class="divMainSearch  layui-card-body">
    <form class="layui-form" action="">

    </form>

    <div class="toolbar" style="margin-top: 5px; padding-left: 30px;"  >
        <!--        <button id="btAdd" class="layui-btn">-->
        <!--            <i class="layui-icon">&#xe608;</i> 添加-->
        <!--        </button>-->
    </div>
</div>



<table id="cmsMain" lay-filter="cmsMain"></table>

<!-- 文章头编缉 -->
<div id="articleDetail" style="display: none">
    <form    class="layui-form"  id="articleDetailfrm">
        <input name="id" hidden>
        <input name="articleDataId" hidden>
        <br>

        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">标题</label>
            <div class="layui-input-block" style="margin-right: 5%;">
                <input name="title"   class="layui-input"    />
            </div>
        </div>




        <!--<div class="layui-form-item">-->
            <!--<label class="layui-form-label">类型</label>-->
            <!--<div class="layui-input-block" style="margin-right: 5%;">-->
                <!--<div id="select1"></div>-->
            <!--</div>-->
        <!--</div>-->


        <!--<div class="layui-form-item layui-form-text">-->
            <!--<label class="layui-form-label">权重</label>-->
            <!--<div class="layui-input-block" style="margin-right: 5%;">-->
                <!--<input type="number" name="weight"   class="layui-input"    />-->
            <!--</div>-->
        <!--</div>-->

        <!--<div class="layui-form-item layui-form-text"   >-->
            <!--<label class="layui-form-label">图片</label>-->
            <!--<div class="layui-input-block" style="margin-right: 5%;">-->
                <!--<input type="hidden" name="image"   id="uploadPath" class="layui-input"     />-->
                <!--<img id="uploadimg" src="" width="50" />-->


                <!--<button type="button" class="layui-btn"  id="uploadUrl"   lay-filter="uploadFile">-->
                    <!--<i class="layui-icon">&#xe67c;</i>选择图片-->
                <!--</button>-->
            <!--</div>-->
        <!--</div>-->




        <div class="layui-row" style="text-algin:center; ">
            <button type="button" style=" margin-left:60%;" 	class="layui-btn layui-btn-primary      layui-layer-close  ">关闭</button>
            <button type="button" class="layui-btn layui-btn-normal"  style=" margin-left:33%;" lay-submit lay-filter="submitarticleDetail" >确认提交</button>
        </div>
        <div style="clear: both; margin-bottom: 10px;"></div>
    </form>
</div>

<!-- 内容编缉 -->
<div id="articleContent" style="display: none">
    <form    class="layui-form"  id="articleContentfrm">
        <input name="id" hidden />
        <input name="titleId" hidden />
        <div style="clear: both; margin-bottom: 0px;"></div>
        <div class="layui-form-item">

            <div class="layui-input-block" style="margin:0 2px;padding:0; height:80%;overflow:auto;">
                <textarea class="form-control" id="content" name="content" placeholder="文章内容"> </textarea>
            </div>
        </div>


        <div class="layui-row" style="text-algin:center;  ">

            <div  style=" margin:50px auto; width:100px;"> <button type="button" class="layui-btn layui-btn-normal"   lay-submit lay-filter="submitarticleContent" >确认提交</button></div>
        </div>
        <div style="clear: both; margin-bottom: 10px;"></div>
    </form>

</div>


<!-- 表格操作列 -->
<script type="text/html" id="cmsarticle-table-bar">
    {{#   if(admin.hasPerm("cms:cmsarticle:update") ){   }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    {{#     } }}
    {{#  if(admin.hasPerm("cms:cmsarticle:delete") ){   }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    {{#     } }}
</script>


<script type="text/html" id="btMain">
    {{#   if(admin.hasPerm("cms:cmsarticle:update") ){   }}
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-xs" lay-event="setContent">设置内容</a>
    {{#     } }}
    {{#  if(admin.hasPerm("cms:cmsarticle:delete") ){   }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    {{#     } }}


</script>

<script type="text/html" id="btImage">
    <image src="{{d.image}}" style="width:50px; " />
</script>

<script type="text/html" id="btISHOW">
    {{# if(!d.hits ){ }}
    否
    {{# } }}

    {{# if(d.hits ){ }}
    是
    {{# } }}
</script>

<script type="text/html" id="toolbar">
    {{#  if(admin.hasPerm("cms:cmsarticle:save")){ }}
    <button id="cmsarticle-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
    {{#     } }}

</script>

<script>
    var admin;
    layui.use(['form', 'table', 'util', 'config', 'admin', 'upload','laytpl','element',"xmSelect" ], function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
        admin = layui.admin;
        var addDialogIndex={};
        //上传
        var upload = layui.upload;
        let laytpl = layui.laytpl;
        let element = layui.element;
        var active={};
        layui.link('assets/css/select2.css');
        layui.link('assets/css/simditor.css');
        var  editor;
        // var select1 = xmSelect.render({
        //     el: '#select1',
        //     language: 'zn',
        //     name: 'categoryIds',
        //     data: [  ]
        // })


        // 渲染表格 cmsMain
        table.render({
            elem: '#cmsMain',
            url: config.base_server + 'sys/agreearticle/list',
            method: 'GET',

            page: true,
            cols: [ [ //表头
                {field:'index', width:80, title: '序号',type: 'numbers'},
                {
                    field : 'title',
                    title : '标题'
                },
                // {
                //     field : 'weight',
                //     title : '权重'
                // }, {
                //     field : 'hits',
                //     title : '访问次数'
                //
                // }, {
                //     field : 'image',
                //     align : 'center',
                //     title : '图片' ,
                //     toolbar : 	"#btImage"
                // },

                {fixed: 'right', align: 'center', toolbar: '#btMain', title: '操作', width: 215}
            ]],
            done: function(res, curr, count){
                //得到当前页码
                currpage=curr;
                // admin.req("/cms/cmscategory/allList",{},function(e){
                //     console.log(e)
                //     if(e.code==0&&e.size>0){
                //         var list=[];
                //         for ( var i in e.data) {
                //             if(i=="remove")continue;
                //             var o={name:e.data[i].name,value:e.data[i].id};
                //             list.push(o);
                //         }
                //         select1. update({data:list});
                //     }
                //
                // } )
            }
        });

        laytpl($("#toolbar")[0].innerHTML).render({ }, function(html){
            $(".layui-card-body .toolbar").append(html);
            element.render('nav');
        });

        // 添加按钮点击事件
        $('#cmsarticle-btn-add').click(function () {
            active.edit()
        });

        //创建一个上传组件 remarkuploadUrl
        upload.render({
            elem: '#uploadUrl'
            ,url:config.base_server+'file/uploadFile'
            ,accept: "images"
            ,before: function(o){
                console.log(o)
            }
            ,done: function(res, index, upload){ //上传后的回调
                if(res.code==0){
                    $('#uploadimg').attr("src", res.data.url);
                    $('#uploadPath').val(res.data.url);
                }
            }
        })

        // 工具条点击事件
        table.on('tool(cmsMain)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { // 修改
                active.edit(data)
            }else if(layEvent === 'setContent'){
                //  articleDetail
                active.setContext(data);
            }  else if (layEvent === 'del') { // 删除
                layer.confirm('确定删除吗？', function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('sys/agreearticle/delete/'+obj.data.id, {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 500});
                            table.reload('cmsMain', {});
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 500});
                        }
                    }, 'delete');
                });
            }
        });

        // //显示表单弹窗
        // var showEditModel = function (data) {
        // 	  var title = data ? '修改用户' : '添加用户';
        //     //修改方法名
        //     if (data){
        //         data.method="update"
        //     }else{
        //     	data={method:"save"};
        //     }
        //
        //     admin.putTempData('t_cmsarticle', data);
        //     admin.popupCenter({
        //         title: title,
        //         path: 'pages/cms/cmsarticle_form.html',
        //         finish: function () {
        //             table.reload('cmsMain', {});
        //         }
        //     });
        // };  layui-btn layui-btn-xs
        active.edit=function (e){
            console.log(e)
            active.open({title:"编缉标题 ",content: $('#articleDetail')},function(){
                formClear($, '#articleDetailfrm');
                if(e) {
                    formLoad($, '#articleDetailfrm', e);
                    $('#uploadimg').attr("src", e.image);
                    // if(e.categoryIds){
                    //     select1.setValue(JSON.parse(e.categoryIds))
                    // }
                }else{
                    // select1.setValue([])
                    // $('#uploadimg').attr("src", 'assets/images/defaultimg.png');
                }
                form.render();
                // table.reload('cmsMain', {});
            },"articleDetail")
        }
        active.open =function(el,sucess,cl){
            var c = 	layer.open({
                type : 1,
                title : el.title,
                area :  [ !el.width?'60%':el.width, !el.height?'60%':el.height ],
                content : el.content,
                scrollbar: true,//是否允许浏览器出现滚动条
                zIndex:99,
                success : sucess?sucess():function(){}
            });


            if(cl)addDialogIndex[cl]=c;
        }


        active.openContext=function(){
            Simditor.locale = 'zh-CN';
            var toolbar = ['title', 'bold', 'italic', 'underline', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'table', '|', 'image',  'link','hr', '|', 'indent', 'outdent', 'alignment'];
            //     var   toolbar = ['title','bold', 'underline','strikethrough','italic','fontScale', 'color',  '|', 'image', 'video','|', 'indent', 'outdent', 'alignment'];

            editor = new Simditor({
                textarea: $('#content'),
                placeholder: '这里输入文字...',
                toolbar: toolbar,
                pasteImage: true,
                defaultImage: 'assets/images/defaultimg.png',
                upload : {
                    url : config.base_server+'/file/simditorUpVedioFile', //文件上传的接口地址
                    params: null, //键值对,指定文件上传接口的额外参数,上传的时候随文件一起提交
                    fileKey: 'file', //服务器端获取文件数据的参数名
                    connectionCount: 3,
                    leaveConfirm: '正在上传文件'
                },
                // upVedioLoad:{
                //     url:config.base_server+'/file/simditorUpVedioFile',
                //     params:null,
                //     fileKey:'file',
                //     uploadBefor: function(file){
                //         if(!file)return false;
                //         console.log(file.type);
                //         var fix =["video/mp4","video/avi","video/ogg"];
                //         return  result = fix.some(function (item) {
                //             return item == file.type;
                //         })
                //
                //         return false;
                //     },
                //     uploadSuccess:function(res){
                //         $(".simditor input[type='file']").attr('capture', 'camera');
                //
                //         editor.focus();
                //
                //     },
                //     unloadFailed:function(e){
                //         console.log(e);
                //         alert("上传失败,请重新上传");
                //     }
                //
                // }
            });

            editor.uploader.on('beforeupload',function (res,file) {

                var img = file.img;
                setTimeout(function () {
                    var height = 300 / img.width * img.height;
                    img.attr('width', 300);
                    img.attr('height', height);
                },1000);
            });


            editor.uploader.on('uploadcomplete',function(res,file,mask){
                //获得上传的文件对象
                var img = file.img;
                var r = JSON.parse(mask);

                if(r.code===0){
                    setTimeout(function () {
                        var height = 300/img.width*img.height;
                        img.attr('width',300);
                        img.attr('height',height);
                    },1000);
                    //重新给img标签的src属性赋值图片路径
                }else {
                    alert("图片上传失败,请重新上传");
                }

            });


            $(".simditor input[type='file']").attr('capture', 'camera');

        }


        active.setContext =function(e){
            console.log(e)
            active.open({title:"内容编缉 ",content: $('#articleContent')},function(){
                formClear($, '#articleContentfrm');
                if(e)  formLoad($, '#articleContentfrm', {titleId:e.id,id:e.articleDataId});
                active.openContext();
                editor.setValue('');
                if(e&&e.articleDataId)
                    admin.req("/sys/agreearticle/datainfo/"+e.articleDataId ,{},function(res){

                        if(res.code==0&&res.data!=undefined){
                            //formLoad($, '#articleContentfrm',res.data);
                            editor.setValue(res.data.content);
                        }
                        form.render();

                    })


            },"articleContent");

        }

        // 搜索按钮点击事件
        $('#cmsarticle-btn-search').click(function () {
            var key = $('#cmsarticle-search-key').val();
            var value = $('#cmsarticle-search-value').val();
            table.reload('cmsMain', {where: {searchKey: key, searchValue: value}});
        });

        form.on('submit(submitarticleContent)', function(data) {
            layer.close(addDialogIndex.articleContent);
            console.log(data)
            admin.req("/sys/agreearticle/datasave",JSON.stringify(data.field),function(e){
                //  layer.close(addDialogIndex);
                if(e.code==0){

                    layer.msg("保存成功！");
                    table.reload('cmsMain', { 	page : { curr :  currpage }   });
                }else{
                    layer.msg(e.msg);
                }
            },"post" );

            return false;

        })


        form.on('submit(submitarticleDetail)', function(data) {
            if(data.field.categoryIds!=null&&data.field.categoryIds!=""&&data.field.categoryIds!=undefined){
                var l =data.field.categoryIds.split(",");
                var list=[];
                l.forEach(function(item,index){
                    list.push(item);
                })
                data.field.categoryIds=JSON.stringify(list);
            }
            layer.close(addDialogIndex.articleDetail);
            admin.req("/sys/agreearticle/save",JSON.stringify(data.field),function(e){
                //  layer.close(addDialogIndex);
                if(e.code==0){
                    table.reload('cmsMain', { 	page : { curr :  currpage }   });
                }
            } ,"post");
        })


    });
</script>
